package com.qiangou.rest;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.entity.MyClass;
import com.entity.Student;
import com.qiangou.service.JerseyService;

/**
 * @author eastmelon
 */

@Component
@Path("/v1")
public class JerseyController {
	@Resource(name="jerseyService")
	JerseyService jerseyService;
/* 
 * @Query
*/	
	@GET
	@Path("/{param}")
	@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML})
	public Response getMessage(@PathParam("param") String msg,@QueryParam("name") String name) {
		System.out.println(name);
		return Response.status(200).entity(jerseyService.getMessage(msg+name)).build();
	}
	
	@GET
	@Path("/json")
	@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML})
	public Response getJSON(@PathParam("param") String msg,@QueryParam("name") String name) {
		Student s=new Student();
		s.setName(name);
		String j=String.valueOf(JSONObject.toJSON(s));
		return Response.status(200).entity(j).build();
	}
	
    /**
     *转成xml的Jar包 jdk1.6+才有
     */
	@GET
	@Path("/xml")
	@Produces({MediaType.APPLICATION_ATOM_XML})
	public Response getXML(@PathParam("param") String msg,@QueryParam("name") String name) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(MyClass.class);    // 获取上下文对象  
        Marshaller marshaller = context.createMarshaller(); // 根据上下文获取marshaller对象  
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");  // 设置编码字符集  
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出，有分行和缩进  
        Student s=new Student();
        s.setName(name);
        Student s2=new Student();
        s2.setName("melon");
        List<Student> sl=new ArrayList<Student>();
        sl.add(s);
        sl.add(s2);
        MyClass mc=new MyClass();
        mc.setClassName("class1");
        mc.setStudent(sl);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        marshaller.marshal(mc, baos);  
        String xmlObj = new String(baos.toByteArray());         // 生成XML字符串  
		return Response.status(200).entity(xmlObj).build();
	}
}
